package patrol.mobile.com.mobilepatrol.activity.office;

import android.content.Intent;
import android.os.Environment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.dl7.recycler.listener.OnRecyclerViewItemClickListener;
import com.dl7.recycler.listener.OnRecyclerViewItemLongClickListener;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImagePreviewDelActivity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import patrol.mobile.com.mobilepatrol.R;
import patrol.mobile.com.mobilepatrol.activity.BaseActivity;
import patrol.mobile.com.mobilepatrol.adapter.ImagePickerAdapter;
import patrol.mobile.com.mobilepatrol.adapter.OtherOfficeDetailAdapter;
import patrol.mobile.com.mobilepatrol.api.Urls;
import patrol.mobile.com.mobilepatrol.bean.DeviceDetailImgBean;
import patrol.mobile.com.mobilepatrol.bean.OtherOfficeDetailBean;
import patrol.mobile.com.mobilepatrol.bean.UpImgInfoBean;
import patrol.mobile.com.mobilepatrol.utils.CommonUtil;
import patrol.mobile.com.mobilepatrol.utils.GsonUtil;
import patrol.mobile.com.mobilepatrol.utils.SDFileHelper;
import patrol.mobile.com.mobilepatrol.utils.StringUtils;
import patrol.mobile.com.mobilepatrol.utils.ToastUtils;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack;
import patrol.mobile.com.mobilepatrol.utils.net.HttpCallBack2;
import patrol.mobile.com.mobilepatrol.utils.net.HttpSender;

public class OtherOfficeDetailActivity extends BaseActivity {

    private static final String TAG = "OtherOfficeActivity";
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_content)
    TextView tvContent;
    @BindView(R.id.tv_leader1)
    TextView tvLeader1;
    @BindView(R.id.tv_leader2)
    TextView tvLeader2;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.seekbar)
    SeekBar seekbar;
    @BindView(R.id.tv_progress)
    TextView tvProgress;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_edit)
    Button tvEdit;
    @BindView(R.id.tv_check)
    Button tvCheck;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    @BindView(R.id.tv_register_org)
    TextView tvRegisterOrg;
    @BindView(R.id.tv_register_time)
    TextView tvRegisterTime;
    @BindView(R.id.tv_register_name)
    TextView tvRegisterName;
    @BindView(R.id.tv_responer)
    TextView tvResponer;
    @BindView(R.id.rb_nor)
    RadioButton rbNor;
    @BindView(R.id.rb_hurrey)
    RadioButton rbHurrey;
    @BindView(R.id.rb_ergent)
    RadioButton rbErgent;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.recyclerView_pic)
    RecyclerView recyclerViewPic;
    @BindView(R.id.tv_cuiban)
    TextView tvCuiban;
    @BindView(R.id.tv_pishi)
    TextView tvPishi;
    @BindView(R.id.tv_end)
    TextView tvEnd;
    @BindView(R.id.lin_btm)
    LinearLayout lin_btm;
    @BindView(R.id.lin_opt)
    LinearLayout lin_opt;
    private OtherOfficeDetailAdapter mAdapter;
    public static final String ID = "ID";
    public static final String MAIN_ID = "MAIN_ID";
    private String id;
    private String mainId;
    private List<OtherOfficeDetailBean.UserScheduleListBean> userScheduleList;
    private OtherOfficeDetailBean data;
    private int delete;
    private List<DeviceDetailImgBean> deviceDetailImgBeans;
    private ArrayList<ImageItem> selImageList;
    private ImagePickerAdapter adapter;
    public static final int IMAGE_ITEM_ADD = -1;
    public static final int REQUEST_CODE_SELECT = 100;
    public static final int REQUEST_CODE_PREVIEW = 101;
    private int limitSize = 4;
    private List<String> imgUUIDs = new ArrayList<>();
    private List<String> imgOldUUIDs = new ArrayList<>();
    private List<UpImgInfoBean> oldImgInfo = new ArrayList<>();
    ArrayList<ImageItem> images = null;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_other_office_detail;
    }

    @Override
    public void initTitle() {
        super.initTitle();
        iv_back.setImageResource(R.mipmap.up_white);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonUtil.exitActivityAndBackAnim(OtherOfficeDetailActivity.this, true);
            }
        });
        tv_center_title.setVisibility(View.VISIBLE);
        tv_center_title.setText("任务详细信息");
        seekbar.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });
    }

    @Override
    public void initData() {
        super.initData();
        id = getIntent().getStringExtra(ID);
        delete = getIntent().getIntExtra("delete", 0);
        if (delete == 1) {
            lin_btm.setVisibility(View.GONE);
            lin_opt.setVisibility(View.VISIBLE);
        }
        mAdapter = new OtherOfficeDetailAdapter(this);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestData();
    }

    private void requestData() {
        HttpSender sender = new HttpSender(this, baseUrl, Urls.TASK_ENTITY);
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        sender.requestPost(map, new HttpCallBack2(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response, String attachList) {
                data = GsonUtil.GsonToBean(response, OtherOfficeDetailBean.class);// TODO: 2019/2/16 接口对应字段不清楚
                tvTitle.setText(data.getTitle());
                tvRegister.setText(data.getReportor());
                tvRegisterOrg.setText(data.getOrgName());
                tvRegisterTime.setText(data.getReportDate());
                switch (data.getUrgent()) {
                    case "紧急":
                        rbHurrey.setChecked(true);
                        break;
                    case "普通":
                        rbNor.setChecked(true);
                        break;
                    case "催办":
                        rbErgent.setChecked(true);
                        break;
                }
                deviceDetailImgBeans = GsonUtil.jsonToList(attachList, DeviceDetailImgBean.class);
                selImageList = new ArrayList<>();
                adapter = new ImagePickerAdapter(OtherOfficeDetailActivity.this, selImageList, limitSize);
                adapter.setOnItemClickListener(new ImagePickerAdapter.OnRecyclerViewItemClickListener() {
                    @Override
                    public void onItemClick(View view, int position) {
                        switch (position) {
                            case IMAGE_ITEM_ADD:
                                break;
                            default:
                                //打开预览
                                Intent intentPreview = new Intent(OtherOfficeDetailActivity.this, ImagePreviewDelActivity.class);
                                intentPreview.putExtra(ImagePicker.EXTRA_IMAGE_ITEMS, (ArrayList<ImageItem>) adapter.getImages());
                                intentPreview.putExtra(ImagePicker.EXTRA_SELECTED_IMAGE_POSITION, position);
                                intentPreview.putExtra(ImagePicker.EXTRA_FROM_ITEMS, true);
                                startActivityForResult(intentPreview, REQUEST_CODE_PREVIEW);
                                break;
                        }
                    }
                });
                recyclerViewPic.setLayoutManager(new GridLayoutManager(OtherOfficeDetailActivity.this, limitSize));
                recyclerViewPic.setHasFixedSize(true);
                recyclerViewPic.setAdapter(adapter);
                images = new ArrayList<>();
                SDFileHelper fileHelper = new SDFileHelper(OtherOfficeDetailActivity.this);
                for (DeviceDetailImgBean deviceDetailImgBean : deviceDetailImgBeans) {
                    String url = baseUrl + deviceDetailImgBean.getFilePath();
                    String replace = url.replace("\\", "/");

                    long currentTime = System.currentTimeMillis();
                    fileHelper.savePicture(currentTime + ".jpg", replace);
                    ImageItem imageItem = new ImageItem();
                    UpImgInfoBean upImgInfoBean = new UpImgInfoBean();
                    try {
                        String filePath = Environment.getExternalStorageDirectory().getCanonicalPath() + "/budejie/" + currentTime + ".jpg";
                        imageItem.path = filePath;
                        selImageList.add(imageItem);
                        imgOldUUIDs.add(deviceDetailImgBean.getId());
                        upImgInfoBean.setId(deviceDetailImgBean.getId());
                        upImgInfoBean.setFileType(deviceDetailImgBean.getFileType());
                        upImgInfoBean.setContentType(deviceDetailImgBean.getContentType());
                        upImgInfoBean.setBusniessId(deviceDetailImgBean.getBusniessId());
                        oldImgInfo.add(upImgInfoBean);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                fileHelper.setOnFileSaveSuccessListener(new SDFileHelper.OnFileSaveSuccessListener() {
                    @Override
                    public void onFileSaveSuccess() {
                        adapter.setImages(selImageList);
                    }
                });
                tvResponer.setText(data.getResponsible());
                tvContent.setText(data.getContext());
                tvLeader1.setText(data.getDirector());
                tvLeader2.setText(data.getResponsible());
                tvTime.setText(data.getTerm());
                userScheduleList = data.getUserScheduleList();
                mAdapter.updateItems(userScheduleList);
                mainId = data.getId();
            }
        });
    }

    @Override
    public void setListener() {
        mAdapter.setOnItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                TaskProgressActivity.show(OtherOfficeDetailActivity.this, false, userScheduleList.get(position).getId(), "", data);
            }
        });
        mAdapter.setOnItemLongClickListener(new OnRecyclerViewItemLongClickListener() {
            @Override
            public boolean onItemLongClick(View view, int position) {
                deleteProgress(userScheduleList.get(position).getId());
                return false;
            }
        });
    }

    private void deleteProgress(String id) {
        HttpSender sender = new HttpSender(this, baseUrl, Urls.TASK_SCHEDULE_DELETE);
        sender.requestPost("id", id, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                requestData();
            }
        });
    }


    //    LeaderInstructionsActivity
    @OnClick({R.id.tv_cuiban, R.id.tv_check, R.id.tv_pishi, R.id.tv_end, R.id.tv_edit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_cuiban:
                requestCuiBanData();
                break;
            case R.id.tv_check:
                Intent intent = new Intent(this, LeaderInstructionsActivity.class);
                intent.putExtra("id", id);
                startActivity(intent);
                break;
            case R.id.tv_pishi:
                Intent intent2 = new Intent(this, LeaderInstructionsActivity.class);
                intent2.putExtra("id", id);
                startActivity(intent2);
                break;
            case R.id.tv_end:
                requestEndData();
                break;
            case R.id.tv_edit:
                if (StringUtils.isEmpty(mainId)) {
                    Toast.makeText(this, "参数获取错误，请重试", Toast.LENGTH_SHORT).show();
                    return;
                }
                TaskProgressActivity.show(this, true, "", mainId, data);
                break;
        }
    }

    private void requestEndData() {
        HttpSender sender = new HttpSender(this, baseUrl, Urls.UPDATEUSERTASKISFINISH);
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        sender.requestPost(map, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                ToastUtils.showToast("操作成功！");
            }
        });
    }

    private void requestCuiBanData() {
        HttpSender sender = new HttpSender(this, baseUrl, Urls.UPDATEUSERTASKURGENT);
        HashMap<String, String> map = new HashMap<>();
        map.put("id", id);
        sender.requestPost(map, new HttpCallBack(sender) {
            @Override
            public void onError(String code, Call call, Exception e) {

            }

            @Override
            public void onResponse(String code, String response) {
                ToastUtils.showToast("操作成功！");
            }
        });
    }
}
